/*
 * Basic no frills app which integrates the ZBar barcode scanner with
 * the camera.
 * 
 * Created by lisah0 on 2012-02-24
 */
package com.darryring.fast.activitys;


import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.ZoomControls;

import com.darryring.fast.R;
import com.darryring.fast.theme.FastTheme;
import com.darryring.fast.util.MoviceSize;
import com.darryring.libcore.Fast;
import com.darryring.libcore.base.BaseAppCompatActivity;
import com.darryring.libcore.util.StringUtil;
import com.darryring.libmodel.entity.theme.ThemeEntity;
import com.darryring.libview.LibCameraPreview;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;

import java.util.List;

/**
 * 扫码,扫描二维码
 */
public class ScancodeActivity extends BaseAppCompatActivity {

    String TAG = "ScancodeActivity";
    private LibCameraPreview mPreview;
    private Handler autoFocusHandler;
    Button scanButton;
    ImageScanner scanner;
    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    }

    private String mResult;
    View animation_line;
    FrameLayout animationFrameLayout;
    AnimatorSet set = null;
    ZoomControls mZoomControls;
    TextView tv_zoom;
    int mZoom;
    int mZoomMax;
    DisplayMetrics mDisplayMetrics;
    private boolean nofocusContinuous = true;

    public void onCreate(Bundle savedInstanceState) {
        FastTheme.fastTheme.setupTheme(this, ThemeEntity.TYPE_NO_ACTION_BAR);
        super.onCreate(savedInstanceState);
        mDisplayMetrics = getResources().getDisplayMetrics();
        setContentView(R.layout.activity_camera_qrcode);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        autoFocusHandler = new Handler();
        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);
        mZoomControls = (ZoomControls) findViewById(R.id.zoomControls);
        tv_zoom = (TextView) findViewById(R.id.tv_zoom);
        mPreview = new LibCameraPreview(this, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout) findViewById(R.id.cameraPreview);
        //
        mPreview.setCallback(new LibCameraPreview.Callback() {

            @Override
            public void initCamera(final Camera _camera) {
                Camera.Parameters _parameters = _camera.getParameters();
                //
                List<String> _focus = _parameters.getSupportedFocusModes();
                if (_focus != null && _focus.size() > 0) {
                    if (_focus.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
                        nofocusContinuous = false;
                    }
                }
                //
                int _maxZoom = _parameters.getMaxZoom();
                int _zoom = _parameters.getZoom();
                mZoom = _zoom;
                mZoomMax = _maxZoom;
                mZoomControls.setIsZoomInEnabled(true);
                mZoomControls.setIsZoomOutEnabled(true);
                if (_maxZoom > 0) {
                    int tempZoom = (mZoomMax / 10) + 2;
                    if (tempZoom > 0) {
                        mZoom = tempZoom;
                        //
                        if (_camera != null) {
                            Camera.Parameters _p = _camera.getParameters();
                            _p.setZoom(mZoom);
                            _camera.setParameters(_p);
                            tv_zoom.setText(StringUtil.toString(String.valueOf(mZoom), "X/", String.valueOf(mZoomMax), "X"));
                        }
                    }
                    mZoomControls.setVisibility(View.VISIBLE);
                    tv_zoom.setText(StringUtil.toString(String.valueOf(mZoom), "X/", String.valueOf(mZoomMax), "X"));
                    if (mZoomControls != null) {
                        //放大
                        mZoomControls.setOnZoomInClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mZoom < mZoomMax) {
                                    if (_camera != null) {
                                        Camera.Parameters _p = _camera.getParameters();
                                        mZoom = (mZoom + 2);
                                        _p.setZoom(mZoom);
                                        _camera.setParameters(_p);
                                        tv_zoom.setText(StringUtil.toString(String.valueOf(mZoom), "X/", String.valueOf(mZoomMax), "X"));
                                    }
                                }
                            }
                        });
                        //缩小
                        mZoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mZoom > 0) {
                                    if (_camera != null) {
                                        Camera.Parameters _p = _camera.getParameters();
                                        mZoom = (mZoom - 2);
                                        _p.setZoom(mZoom);
                                        _camera.setParameters(_p);
                                        tv_zoom.setText(StringUtil.toString(String.valueOf(mZoom), "X/", String.valueOf(mZoomMax), "X"));
                                    }
                                }
                            }
                        });
                        mZoomControls.show();
                    }
                } else {
                    mZoomControls.setVisibility(View.GONE);
                    tv_zoom.setVisibility(View.GONE);
                }
                autoFocusHandler.postDelayed(mAutoFocusRunnable, 1000);
                //-------------------------------------------------------------
                //-------------------------------------------------------------

            }
        });

        //
        preview.addView(mPreview);
        animation_line = findViewById(R.id.animation_line);
        scanButton = (Button) findViewById(R.id.btn_qrcode_scan);
        animationFrameLayout = (FrameLayout) findViewById(R.id.animation_layer);

        ViewGroup.LayoutParams _params = animationFrameLayout.getLayoutParams();
        MoviceSize _size = MoviceSize.makeHeight(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels, 700);
        _params.width = _size.height;
        _params.height = _size.height;

        scanButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (barcodeScanned) {
                    barcodeScanned = false;
                    mPreview.setPreviewCallback(previewCb);
                    mPreview.startPreview();
                    previewing = true;
                    mPreview.autoFocus(autoFocusCB);
                    scanButton.setVisibility(View.GONE);
                }
            }
        });
        //
        //===============================================================================
        if (FastTheme.fastTheme.theme() != null) {
            TypedArray ta = getTheme().obtainStyledAttributes(R.styleable.FastColorTheme);
            int _selectColor = ta.getColor(R.styleable.FastColorTheme_colorFastNomal, 0);
            animation_line.setBackgroundColor(_selectColor);
            ta.recycle();
        }
        //==============================================================================
    }

    final Runnable mAutoFocusRunnable = new Runnable() {
        @Override
        public void run() {
            if (mPreview != null) {
                mPreview.cancelAutoFocus();
            }
            if (nofocusContinuous) {
                //设备支持持续对焦
                autoFocusHandler.postDelayed(this, 1000);
            }
        }
    };

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setupScanAnimationLine();
    }

    public void onPause() {
        super.onPause();
        if (mPreview != null) {
            mPreview.releaseCamera();
        }
        if (set != null && set.isStarted()) {
            set.cancel();
            set = null;
        }
    }

    private void setupScanAnimationLine() {
        if (animation_line != null) {
            set = new AnimatorSet();
            ViewGroup.LayoutParams _params = animationFrameLayout.getLayoutParams();
            ObjectAnimator o1 = ObjectAnimator.ofFloat(animation_line, "translationY", 0, _params.height);
            o1.setRepeatCount(10000);
            o1.setRepeatMode(ValueAnimator.INFINITE);
            set.play(o1);
            set.setDuration(4 * 1000);
            set.start();
        }
    }

    private void stopScanAnimationLine() {
        if (set != null && set.isStarted()) {
            set.cancel();
            set = null;
        }
    }


    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            Fast.logger.i(TAG, "doAutoFocus-->run....");
            if (previewing && mPreview != null) {
                mPreview.autoFocus(autoFocusCB);
            }
        }
    };

    PreviewCallback previewCb = new PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {
            Camera.Parameters parameters = camera.getParameters();
            Camera.Size size = parameters.getPreviewSize();

            Image barcode = new Image(size.width, size.height, "Y800");
//            rect.left ,rect.top, rect.width(),rect.height()
            int _scanWidth = animationFrameLayout.getWidth();
            int _scanHeight = animationFrameLayout.getHeight();
            MoviceSize _displaySize = MoviceSize.make(mDisplayMetrics.widthPixels, mDisplayMetrics.heightPixels,
                    size.width, size.height, _scanWidth, _scanHeight);

            if (_scanWidth > 0 && _scanHeight > 0) {
                int _max = Math.max(_displaySize.width, _displaySize.height);
                int _x = (size.width - _max) / 2;
                int _y = (size.height - _max) / 2;
                barcode.setCrop(_x, _y, _max, _max);
            } else {
                barcode.setCrop(200, 200, size.width - 200, size.height - 200);
            }

            barcode.setData(data);

            int result = scanner.scanImage(barcode);

            if (result != 0) {
                previewing = false;
                mPreview.setPreviewCallback(null);
                mPreview.stopPreview();
                stopScanAnimationLine();
                SymbolSet syms = scanner.getResults();
                for (Symbol sym : syms) {
                    mResult = sym.getData();
                    barcodeScanned = true;
                }
            }
            if (mResult != null) {
                Dialog _dialog = new AlertDialog.Builder(ScancodeActivity.this).setMessage(mResult).setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        retartScan();
                    }
                }).setCancelable(false).create();
                _dialog.show();
            }
        }
    };

    void retartScan() {
        setupScanAnimationLine();
        if (barcodeScanned) {
            barcodeScanned = false;
            mResult = null;
            mPreview.setPreviewCallback(previewCb);
            mPreview.startPreview();
            previewing = true;
            mPreview.autoFocus(autoFocusCB);
        }

    }

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            Fast.logger.i(TAG, "autoFocusCB-->onAutoFocus-->" + success);
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };


}
